import React, { useState, useEffect } from 'react';
import { get, post, put, del } from '../utils/api';
import { useAuth } from '../contexts/AuthContext';
import './Assets.css';

interface Asset {
  id: string;
  name: string;
  category: string;
  model: string;
  serialNumber: string;
  purchaseDate: string;
  purchasePrice: number;
  status: 'active' | 'maintenance' | 'retired';
  location: string;
  assignedTo?: string;
  description?: string;
  createdAt: string;
  updatedAt: string;
}

interface AssetFormData {
  name: string;
  category: string;
  model: string;
  serialNumber: string;
  purchaseDate: string;
  purchasePrice: number;
  status: 'active' | 'maintenance' | 'retired';
  location: string;
  assignedTo: string;
  description: string;
}

const Assets: React.FC = () => {
  const { user } = useAuth();
  const [assets, setAssets] = useState<Asset[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingAsset, setEditingAsset] = useState<Asset | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');

  const [formData, setFormData] = useState<AssetFormData>({
    name: '',
    category: '',
    model: '',
    serialNumber: '',
    purchaseDate: '',
    purchasePrice: 0,
    status: 'active',
    location: '',
    assignedTo: '',
    description: ''
  });

  useEffect(() => {
    fetchAssets();
  }, []);

  const fetchAssets = async () => {
    try {
      setLoading(true);
      const response = await get('/assets');
      if (response.success) {
        // 后端返回的数据结构是 { success: true, data: { assets: [...], pagination: {...} } }
        setAssets(response.data.assets || []);
      } else {
        setError('获取资产列表失败');
      }
    } catch (error) {
      console.error('Failed to fetch assets:', error);
      setError('获取资产列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      if (editingAsset) {
        const response = await put(`/assets/${editingAsset.id}`, formData);
        if (response.success) {
          await fetchAssets();
          resetForm();
          setShowModal(false);
        } else {
          setError(response.message || '更新资产失败');
        }
      } else {
        const response = await post('/assets', formData);
        if (response.success) {
          await fetchAssets();
          resetForm();
          setShowModal(false);
        } else {
          setError(response.message || '添加资产失败');
        }
      }
    } catch (error) {
      setError('操作失败，请稍后重试');
    }
  };

  const handleEdit = (asset: Asset) => {
    setEditingAsset(asset);
    setFormData({
      name: asset.name,
      category: asset.category,
      model: asset.model,
      serialNumber: asset.serialNumber,
      purchaseDate: asset.purchaseDate.split('T')[0],
      purchasePrice: asset.purchasePrice,
      status: asset.status,
      location: asset.location,
      assignedTo: asset.assignedTo || '',
      description: asset.description || ''
    });
    setShowModal(true);
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm('确定要删除这个资产吗？')) {
      return;
    }

    try {
      const response = await del(`/assets/${id}`);
      if (response.success) {
        await fetchAssets();
      } else {
        setError(response.message || '删除资产失败');
      }
    } catch (error) {
      setError('删除失败，请稍后重试');
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      category: '',
      model: '',
      serialNumber: '',
      purchaseDate: '',
      purchasePrice: 0,
      status: 'active',
      location: '',
      assignedTo: '',
      description: ''
    });
    setEditingAsset(null);
    setError('');
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name === 'purchasePrice' ? parseFloat(value) || 0 : value
    }));
  };

  // 过滤资产
  const filteredAssets = assets.filter(asset => {
    const matchesSearch = asset.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         asset.category.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         asset.serialNumber.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = filterStatus === 'all' || asset.status === filterStatus;
    
    return matchesSearch && matchesStatus;
  });

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY'
    }).format(value);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN');
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'active':
        return '使用中';
      case 'maintenance':
        return '维护中';
      case 'retired':
        return '已退役';
      default:
        return status;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return 'success';
      case 'maintenance':
        return 'warning';
      case 'retired':
        return 'danger';
      default:
        return 'secondary';
    }
  };

  if (loading) {
    return (
      <div className="assets-loading">
        <div className="spinner"></div>
        <p>加载资产数据...</p>
      </div>
    );
  }

  return (
    <div className="assets">
      <div className="assets-header">
        <h1>资产管理</h1>
        <button 
          onClick={() => setShowModal(true)} 
          className="btn btn-primary"
        >
          <span className="btn-icon">➕</span>
          添加资产
        </button>
      </div>

      {error && (
        <div className="alert alert-error">
          {error}
          <button onClick={() => setError('')} className="alert-close">×</button>
        </div>
      )}

      {/* 搜索和过滤 */}
      <div className="assets-controls">
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索资产名称、类别或序列号..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="search-input"
          />
        </div>
        
        <div className="filter-box">
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)}
            className="filter-select"
          >
            <option value="all">所有状态</option>
            <option value="active">使用中</option>
            <option value="maintenance">维护中</option>
            <option value="retired">已退役</option>
          </select>
        </div>
      </div>

      {/* 资产列表 */}
      <div className="assets-list">
        {filteredAssets.length > 0 ? (
          <div className="assets-table">
            <table>
              <thead>
                <tr>
                  <th>资产名称</th>
                  <th>类别</th>
                  <th>型号</th>
                  <th>序列号</th>
                  <th>状态</th>
                  <th>位置</th>
                  <th>购买价格</th>
                  <th>购买日期</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {filteredAssets.map((asset) => (
                  <tr key={asset.id}>
                    <td className="asset-name">{asset.name}</td>
                    <td>{asset.category}</td>
                    <td>{asset.model}</td>
                    <td className="serial-number">{asset.serialNumber}</td>
                    <td>
                      <span className={`status-badge ${getStatusColor(asset.status)}`}>
                        {getStatusText(asset.status)}
                      </span>
                    </td>
                    <td>{asset.location}</td>
                    <td className="price">{formatCurrency(asset.purchasePrice)}</td>
                    <td className="date">{formatDate(asset.purchaseDate)}</td>
                    <td className="actions">
                      <button
                        onClick={() => handleEdit(asset)}
                        className="btn btn-sm btn-secondary"
                        title="编辑"
                      >
                        ✏️
                      </button>
                      <button
                        onClick={() => handleDelete(asset.id)}
                        className="btn btn-sm btn-danger"
                        title="删除"
                      >
                        🗑️
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="empty-state">
            <div className="empty-icon">📦</div>
            <h3>
              {searchTerm || filterStatus !== 'all' ? '没有找到匹配的资产' : '暂无资产'}
            </h3>
            <p>
              {searchTerm || filterStatus !== 'all' 
                ? '请尝试调整搜索条件或过滤器' 
                : '开始添加您的第一个资产'
              }
            </p>
            {(!searchTerm && filterStatus === 'all') && (
              <button 
                onClick={() => setShowModal(true)} 
                className="btn btn-primary"
              >
                添加资产
              </button>
            )}
          </div>
        )}
      </div>

      {/* 添加/编辑模态框 */}
      {showModal && (
        <div className="modal-overlay" onClick={() => {
          setShowModal(false);
          resetForm();
        }}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2>{editingAsset ? '编辑资产' : '添加资产'}</h2>
              <button 
                onClick={() => {
                  setShowModal(false);
                  resetForm();
                }}
                className="modal-close"
              >
                ×
              </button>
            </div>

            <form onSubmit={handleSubmit} className="modal-form">
              <div className="form-row">
                <div className="form-group">
                  <label className="form-label">
                    资产名称 <span className="required">*</span>
                  </label>
                  <input
                    type="text"
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    className="form-input"
                    required
                  />
                </div>

                <div className="form-group">
                  <label className="form-label">
                    类别 <span className="required">*</span>
                  </label>
                  <input
                    type="text"
                    name="category"
                    value={formData.category}
                    onChange={handleChange}
                    className="form-input"
                    required
                  />
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label className="form-label">型号</label>
                  <input
                    type="text"
                    name="model"
                    value={formData.model}
                    onChange={handleChange}
                    className="form-input"
                  />
                </div>

                <div className="form-group">
                  <label className="form-label">
                    序列号 <span className="required">*</span>
                  </label>
                  <input
                    type="text"
                    name="serialNumber"
                    value={formData.serialNumber}
                    onChange={handleChange}
                    className="form-input"
                    required
                  />
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label className="form-label">购买日期</label>
                  <input
                    type="date"
                    name="purchaseDate"
                    value={formData.purchaseDate}
                    onChange={handleChange}
                    className="form-input"
                  />
                </div>

                <div className="form-group">
                  <label className="form-label">购买价格</label>
                  <input
                    type="number"
                    name="purchasePrice"
                    value={formData.purchasePrice}
                    onChange={handleChange}
                    className="form-input"
                    min="0"
                    step="0.01"
                  />
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label className="form-label">状态</label>
                  <select
                    name="status"
                    value={formData.status}
                    onChange={handleChange}
                    className="form-select"
                  >
                    <option value="active">使用中</option>
                    <option value="maintenance">维护中</option>
                    <option value="retired">已退役</option>
                  </select>
                </div>

                <div className="form-group">
                  <label className="form-label">位置</label>
                  <input
                    type="text"
                    name="location"
                    value={formData.location}
                    onChange={handleChange}
                    className="form-input"
                  />
                </div>
              </div>

              <div className="form-group">
                <label className="form-label">分配给</label>
                <input
                  type="text"
                  name="assignedTo"
                  value={formData.assignedTo}
                  onChange={handleChange}
                  className="form-input"
                  placeholder="分配给用户"
                />
              </div>

              <div className="form-group">
                <label className="form-label">描述</label>
                <textarea
                  name="description"
                  value={formData.description}
                  onChange={handleChange}
                  className="form-textarea"
                  rows={3}
                  placeholder="资产描述信息"
                />
              </div>

              <div className="modal-actions">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="btn btn-secondary"
                >
                  取消
                </button>
                <button type="submit" className="btn btn-primary">
                  {editingAsset ? '更新' : '添加'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default Assets;
